import { useMemo, useLayoutEffect } from 'react'
import { getDefaultStore, useAtomValue } from 'jotai'
import { activeThemeAtom, themeAtom } from '../atoms/settingAtoms'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import { Theme } from '@/types'

// 匹配系统暗黑主题状态
const mediaQuery = window.matchMedia('(prefers-color-scheme:dark)')
mediaQuery.addEventListener('change', () => {
  switchTheme(Theme.FollowSystem)
})

export const switchTheme = async (theme: Theme) => {
  const store = getDefaultStore()
  if (theme === Theme.FollowSystem) {
    const isDark = mediaQuery.matches
    store.set(activeThemeAtom, isDark ? 'dark' : 'light')
  }
  else {
    store.set(activeThemeAtom, theme === Theme.DarkMode ? 'dark' : 'light')
  }
}

export default function useAppTheme() {
  const theme = useAtomValue(themeAtom)
  const activeTheme = useAtomValue(activeThemeAtom)

  useLayoutEffect(() => {
    switchTheme(theme)
  }, [theme])

  useLayoutEffect(() => {
    if (activeTheme === 'dark') {
      document.documentElement.classList.add('dark')
    }
    else {
      document.documentElement.classList.remove('dark')
    }
  }, [activeTheme])

  const themeObj = useMemo(() => createTheme({
    // https://mui.com/material-ui/customization/default-theme/
    // https://mui.com/material-ui/customization/theming/#theme-configuration-variables
    // https://zenoo.github.io/mui-theme-creator/
    palette: {
      mode: activeTheme,
      primary: {
        main: activeTheme === 'dark' ? '#0A97B0' : '#0A5EB0',
      },
      secondary: {
        main: '#E85C0D',
      },
      info: {
        main: '#00CCDD',
      },
      background: {
        default: activeTheme === 'dark' ? '#212121' : '#ffffff',
        paper: activeTheme === 'dark' ? '#1e1e1e' : '#fff',
      },
    },
  }), [activeTheme])

  return { themeObj, ThemeProvider }
}
